package com.vogue.supplymall.account.controller;

import com.vogue.supplymall.account.domain.dto.AddressDTO;
import com.vogue.supplymall.account.domain.model.Address;
import com.vogue.supplymall.account.domain.service.AddressService;
import com.vogue.supplymall.common.constant.ConstantBean;
import com.vogue.supplymall.common.domain.dto.ControllerResultInfo;
import com.vogue.supplymall.common.domain.dto.OrganInfo;
import com.vogue.supplymall.common.domain.dto.UserInfo;
import com.vogue.supplymall.common.domain.validate.Regex;
import com.vogue.supplymall.common.exception.DataNotFindException;
import com.vogue.supplymall.common.exception.NoControlOfDataException;
import com.vogue.supplymall.shop.common.CodeTransformUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by 崔岳 on 2018-1-10. <br>
 * <p>
 * 收货地址查询修改
 */
@Validated
@RestController
public class AddressController extends BaseController {

    @Resource
    private CodeTransformUtils codeTransformUtils;

    @Autowired
    private AddressService addressService;

    /**
     * 收获地址列表
     *
     * @param appver  版本号
     * @param request 请求对象
     * @return ResponseEntity<List<AddressDTO>>
     */
    @RequestMapping(value = "/is/{appver}/account/addr/list", method = RequestMethod.POST)
    public ResponseEntity<List<AddressDTO>> list(
            @PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
            HttpServletRequest request) {
        UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        OrganInfo organ = new OrganInfo();
        if (user.getOrganInfo() != null) {
            organ = user.getOrganInfo();
        }
        Long orgainid = 0L;
        if (organ.getId() != null) {
            orgainid = organ.getId();
        }
        List<Address> list = addressService.queryList(user.getSyscodeid(), orgainid);
        List<AddressDTO> dtolist = new ArrayList<AddressDTO>();
        AddressDTO dto = null;
        for (Address address : list) {
            dto = new AddressDTO();
            BeanUtils.copyProperties(address, dto);
            dto.setId(address.getId());
            if (codeTransformUtils.getAreaName(address.getProvince()) != null) {
                dto.setProvincename(codeTransformUtils.getAreaName(address.getProvince()).get("province"));
            }
            if (codeTransformUtils.getCityName(address.getCity()) != null) {
                dto.setCityname(codeTransformUtils.getCityName(address.getCity()));
            }
            dtolist.add(dto);
        }
        return new ResponseEntity<List<AddressDTO>>(dtolist, HttpStatus.OK);
    }

    /**
     * 新增修改收货地址
     *
     * @param appver     版本号
     * @param addressDTO 地址信息
     * @param request    请求对象
     * @return ResponseEntity<AddressDTO> response entity
     */
    @RequestMapping(value = "/is/{appver}/account/addr/addupdate", method = RequestMethod.POST)
    public ResponseEntity<AddressDTO> addupdate(
            @PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
            @Validated @RequestBody AddressDTO addressDTO, HttpServletRequest request) {
        UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        Address address = null;
        if (addressDTO != null) {
            if (addressDTO.getId() == null) {
                address = new Address();
                BeanUtils.copyProperties(addressDTO, address);
                address.setId(null);
                address.setUserid(user.getLoginId());
                address.setSyscodeid(user.getSyscodeid());
                OrganInfo organ = new OrganInfo();
                if (user.getOrganInfo() != null) {
                    organ = user.getOrganInfo();
                }
                if (organ.getId() == null) {
                    address.setOrganid(0L);
                } else {
                    address.setOrganid(organ.getId());
                }
            } else {
                address = addressService.get(addressDTO.getId());
                if (address != null) {
                    BeanUtils.copyProperties(addressDTO, address);
                }
            }
            if (address != null) {
                addressService.saveOrUpdate(address);
                addressDTO.setId(address.getId());
            }
        }
        return new ResponseEntity<AddressDTO>(addressDTO, HttpStatus.OK);
    }

    /**
     * 删除指定id的收货地址
     *
     * @param appver  版本号
     * @param id      地址记录id
     * @param request 请求对象
     * @return ResponseEntity<ControllerResultInfo> response entity
     */
    @RequestMapping(value = "/is/{appver}/account/addr/del/{id}", method = RequestMethod.POST)
    public ResponseEntity<ControllerResultInfo> del(
            @PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
            @PathVariable("id") Long id, HttpServletRequest request) {
        UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        Address address = addressService.get(id);
        if (address != null && user.getLoginId().equals(address.getUserid())) {
            addressService.delete(id);
        } else {
            if (address == null) {
                throw new DataNotFindException(messageSourceUtils.getMessage(
                        com.vogue.supplymall.common.constant.ConstantBean.GLOBAL_SYSTEM
                                + "addr", null));
            } else {
                throw new NoControlOfDataException();
            }
        }
        ControllerResultInfo result = new ControllerResultInfo();
        result.setData("ok");
        return new ResponseEntity<ControllerResultInfo>(result, HttpStatus.OK);
    }

    /**
     * 将指定id的收货地址设置成默认
     *
     * @param appver  版本号
     * @param id      地址对象id
     * @param request 请求对象
     * @return ResponseEntity<ControllerResultInfo>
     */
    @RequestMapping(value = "/is/{appver}/account/addr/default/{id}", method = RequestMethod.POST)
    public ResponseEntity<ControllerResultInfo> setdefault(
            @PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
            @PathVariable("id") Long id, HttpServletRequest request) {
        UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        Address address = addressService.get(id);
        if (address != null && user.getLoginId().equals(address.getUserid())) {
            addressService.setupDefault(id, user.getLoginId(), user.getLoginUserType());
        } else {
            if (address == null) {
                throw new DataNotFindException(messageSourceUtils.getMessage(
                        com.vogue.supplymall.common.constant.ConstantBean.GLOBAL_SYSTEM
                                + "addr", null));
            } else {
                if (address.getType() == ConstantBean.EnumAddressType.SHOP.getCode() && address.getOrganid() != null
                        && user.getOrganInfo() != null
                        && address.getOrganid().equals(user.getOrganInfo().getId())) {
                    addressService.setupDefaultForOrgan(id, user.getOrganInfo().getId());
                } else {
                    throw new NoControlOfDataException();
                }
            }
        }
        ControllerResultInfo result = new ControllerResultInfo();
        result.setData("ok");
        return new ResponseEntity<ControllerResultInfo>(result, HttpStatus.OK);
    }

    /**
     * 查找指定id的地址对象
     *
     * @param appver  版本号
     * @param id      地址对象id
     * @param request 请求对象
     * @return ResponseEntity<AddressDTO> response entity
     */
    @RequestMapping(value = "/is/{appver}/account/addr/edit/{id}", method = RequestMethod.POST)
    public ResponseEntity<AddressDTO> edit(
            @PathVariable("appver") @Regex(name = "appver", regexcontent = "vernum") String appver,
            @PathVariable("id") Long id, HttpServletRequest request) {
        UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        Address address = addressService.get(id);
        if (address == null) {
            throw new DataNotFindException(messageSourceUtils.getMessage(
                    com.vogue.supplymall.common.constant.ConstantBean.GLOBAL_SYSTEM
                            + "addr", null));
        }
        AddressDTO dto = new AddressDTO();
        if (address != null && user.getLoginId().equals(address.getUserid())) {
            BeanUtils.copyProperties(address, dto);
            dto.setId(address.getId());
            if (codeTransformUtils.getAreaName(address.getProvince()) != null) {
                dto.setProvincename(codeTransformUtils.getAreaName(address.getProvince()).get("province"));
            }
            if (codeTransformUtils.getCityName(address.getCity()) != null) {
                dto.setCityname(codeTransformUtils.getCityName(address.getCity()));
            }
        } else {
            throw new NoControlOfDataException();
        }
        return new ResponseEntity<AddressDTO>(dto, HttpStatus.OK);
    }
}
